Ext.onReady(function() {
	Ext.tip.QuickTipManager.init();
	var store = Ext.create('Ext.data.Store',{
		groupField: 'ACTIONMONTH',
		fields: [
		    {name: 'ID', type:'string'},
		    {name: 'PID', type:'string'},
		    {name: 'ACTIONMONTH', type:'string'},
            {name: 'ACTIONDATE', type:'date'},
            {name: 'ACTIONDATESTR', type:'string'},
            {name: 'SPENDTYPE', type:'string'},
            {name: 'SUBSPENDNAME', type:'string'},
            {name: 'MONEY', type:'float'}
        ],
        sorters: [{
            property: 'ACTIONDATE',
            direction: 'DESC'
        }]
	});
	
	var spendTypeStore = Ext.create('Ext.data.Store',{
	    fields: [
	            {name: 'id', type: 'string'},
	            {name: 'text', type: 'string'},
	        ],
		 proxy:{
			type: 'ajax',
			url : getPath("/ab/po/houseKeeperDetail.do"),
			extraParams : {
            	"md":"readSpendType"
            },
			reader : {
				type : 'json',
				root : 'spendtype'
			}
		 }
	});
	
	var month = Ext.create('Ext.ux.MonthField', {
		value: new Date(),
		fieldLabel: str_housekeeperdetail_tjmonth,
		editable: false,
		labelWidth:80
	});
	
	var filters = Ext.create('Ext.ux.grid.FiltersFeature',{
        encode: false,
        local: true,
        filters: [
            {
                type: 'string',
                dataIndex: 'SUBSPENDNAME'
            },
            {
                type: 'list',
                dataIndex: 'SPENDTYPE',
                store:spendTypeStore
            },
            {
            	type: 'numeric',
            	dataIndex: 'MONEY'
            },
            {
            	type: 'date',
            	dataIndex: 'ACTIONDATE',
            	renderer: Ext.util.Format.dateRenderer('Y-m-d')
            }
        ]
    });
	
	var grouping = Ext.create('Ext.grid.feature.GroupingSummary',{
		groupHeaderTpl: '{name}',
        hideGroupedHeader: true,
        enableGroupingMenu: false
    });
	
	var cellEditing = Ext.create('Ext.grid.plugin.CellEditing', {
        clicksToEdit: 1,
        listeners:{
        	edit:{
        		fn:onSpendTypeEdit
        	}
        }
    });
	
	var grid = Ext.create('Ext.grid.Panel', {
		split: true,
		loadMask : true,
		multiSelect : true,
		store:store,
		border: false,
		plugins: [cellEditing],
		features: [
		   filters,
		   grouping
		],
		columns: [
          {
              xtype: 'rownumberer',
              width: 30,
              hideable: false
          },
          {
        	  xtype: 'gridcolumn',
        	  text: 'ID',
        	  hidden: true,
              width: 0,
              defaultWidth: 0,
              dataIndex: 'ID',
              hideable: false
          },
          {
        	  xtype: 'gridcolumn',
        	  text: 'PID',
        	  hidden: true,
              width: 0,
              defaultWidth: 0,
              dataIndex: 'ID',
              hideable: false
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'ACTIONMONTH',
              hidden: true,
              text: str_housekeeperdetail_month,
              width : 80
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'SPENDTYPE',
              text: str_housekeeperdetail_costtype,
              width : 100,
              summaryType: 'count',
              summaryRenderer: function(value, summaryData, dataIndex) {
                  return ((value === 0 || value > 1) ? '(' + value + ' Items)' : '(1 Items)');
              },
              editor : {
        		  xtype: 'combobox',
                  typeAhead: true,
                  triggerAction: 'all',
                  selectOnTab: true,
                  displayField: 'text',
                  valueField: 'id',
                  editable: false,
        		  store: spendTypeStore,
                  lazyRender: true
        	  }
          },
          {
              xtype: 'gridcolumn',
              dataIndex: 'SUBSPENDNAME',
              text: str_housekeeperdetail_subentity,
              width : 100
          },
          {
        	  xtype: 'numbercolumn',
              dataIndex: 'MONEY',
              flex: 1,
              text: str_housekeeperdetail_amount,
              summaryType: 'sum',
              summaryRenderer: function(value) {
                  return '￥' + value;
              }
          },
          {
              xtype: 'datecolumn',
              dataIndex: 'ACTIONDATE',
              text: str_housekeeperdetail_costdate,
              format: 'Y-m-d',
              width : 80
          }
        ],
	    dockedItems: [
		  {
		      xtype: 'toolbar',
		      dock: 'top',
		      items: [
		          month,'-',
		          {
		              xtype: 'button',
		              text: str_common_query,
	                  listeners: {
	                      click: {
	                          fn: query
	                      }
	                  }
		          },
		          {
                      xtype: 'tbseparator'
                  },
                  {
		              xtype: 'button',
		              text: str_housekeeperdetail_export,
	                  listeners: {
	                      click: {
	                          fn: exportExcel
	                      }
	                  }
		          },
		          {
                      xtype: 'tbseparator'
                  },
                  {
                	  text: str_housekeeperdetail_fenzu,
                      menu: [{
                    	  text: str_housekeeperdetail_yearmonth,
                          handler: function(){
                        	  store.group("ACTIONMONTH");
                        	  currentGroupField = "ACTIONMONTH";
                        	  queryChart("SPENDTYPE");
                          }
                      },{
                    	  text: str_housekeeperdetail_costtype,
                          handler: function(){
                        	  store.group("SPENDTYPE");
                        	  currentGroupField = "SPENDTYPE";
                        	  queryChart("SPENDTYPE");
                          }
                      },{
                    	  text: str_housekeeperdetail_subentity,
                          handler: function(){
                        	  store.group("SUBSPENDNAME");
                        	  currentGroupField = "SUBSPENDNAME";
                        	  queryChart("SUBSPENDNAME");
                          }
                      },{
                    	  text: str_housekeeperdetail_costdate,
                          handler: function(){
                        	  store.group("ACTIONDATE");
                        	  currentGroupField = "ACTIONDATE";
                        	  queryChart("ACTIONDATESTR");
                          }
                      }]
                  }
		      ]
		   },
		]
	});
	
	function onSpendTypeEdit(editor, e){
		var newvalue = e.value;
		var orivalue = e.originalValue;
		if(newvalue == orivalue){
			return true;
		}
		if(newvalue == null){
			Ext.MessageBox.alert(str_common_error,str_housekeeperdetail_costypenull);
			return false;
		}
		Ext.Ajax.request({
		  url : getPath('/ab/po/houseKeeperDetail.do'),
		  actionMethods: 'POST',
		  params : {
			  md: "updateSpendType",
              SPENDTYPE : newvalue,
              ID: e.record.data['ID'],
              SUBSPENDNAME: e.record.data['SUBSPENDNAME']
		  },
		  success : function(response) {  
              var ret = Ext.JSON.decode(response.responseText);
              if(!ret.success){
            	  Ext.MessageBox.alert(str_common_error,ret.msg);
              }
          }
		});
	}
	
	var chartStore = Ext.create('Ext.data.Store',{
		fields: [
		    {name: 'RATE', type:'float'},
            {name: 'CNT', type:'int'},
            {name: 'DISPLAY', type:'string'},
            {name: 'MONEY', type:'float'},
            {name: 'LEN', type:'int'}
        ]
	});
	
	var currentChartField = "ACTIONDATESTR";
	var currentGroupField = "ACTIONDATE";
	function queryChart(field,month){
		curreentChartField = field;
		chartStore.setProxy({
			type : 'ajax',
			url : getPath("/ab/po/houseKeeperDetail.do"),
			extraParams : {
            	"md":"rchart",
            	"ACTIONMONTH":month ? month : store.getAt(0).data['ACTIONMONTH'],
            	"GROUPFIELD":field
            },
			reader : {
				type : 'json',
				root : 'housekeeperdetail',
				totalProperty : 'totalCount'
			}
		});
		chartStore.load();
	}
	
	var currentQueryMonth = '';
	
	function exportExcel(){
		if(currentQueryMonth != month.getRawValue()) {
			Ext.MessageBox.alert(str_common_warn,str_housekeeperdetail_plsquery);
			return;
		}
		if(store.getTotalCount() != 0) {
			window.open(getPath('/ab/po/houseKeeperDetail.do?md=exportExcel&month=' + month.getRawValue()));
		}
	}
	
	function query(){
		currentQueryMonth = month.getRawValue();
		store.setProxy({
			type : 'ajax',
			url : getPath("/ab/po/houseKeeperDetail.do"),
			extraParams : {
            	"md":"r",
            	"ACTIONMONTH":month.getRawValue()
            },
			reader : {
				type : 'json',
				root : 'housekeeperdetail',
				totalProperty : 'totalCount'
			}
		});
		store.load();
		store.group(currentGroupField);
		queryChart(currentChartField ,month.getRawValue());
	}
	
	var monthChart = Ext.create('Ext.chart.Chart', {
		id: 'chartCmp',
        xtype: 'chart',
        style: 'background:#fff',
        animate: true,
        shadow: true,
        store: chartStore,
        series: [{
            type: 'pie',
            animate: true,
            angleField: 'RATE', //bind angle span to visits
            lengthField: 'LEN', //bind pie slice length to views
            highlight: {
              segment: {
                margin: 20
              }
            },
            label: {
                field: 'DISPLAY',   //bind label text to name
                display: 'rotate', //rotate labels (also middle, out).
                font: '14px Arial',
                contrast: true
            },                                
            style: {
                'stroke-width': 1,
                'stroke': '#fff'
            },
            tips: {
                trackMouse: true,
                width: 200,
                renderer: function(storeItem, item) {
                  this.setTitle(storeItem.get('DISPLAY'));
                  this.update("￥" + storeItem.get('MONEY') + str_housekeeperdetail_account + storeItem.get('CNT') + str_housekeeperdetail_percent + storeItem.get('RATE') + "%");
                }
            },
            //add renderer
            renderer: function(sprite, record, attr, index, store) {
                var value = (index >> 0) % 9;
                var color = [ "#94ae0a", "#115fa6","#a61120", "#ff8809", "#ffd13e", "#a61187", "#24ad9a", "#7c7474", "#a66111"][value];
                return Ext.apply(attr, {
                    fill: color
                });
            },
            listeners: {
                'itemmouseup': function(item) {
                	var index = item.index;
                	var val = chartStore.getAt(index).data["DISPLAY"];
                	var selectionModel = grid.getSelectionModel();
                	var range = getSelectionRange(store, curreentChartField, val);
                	selectionModel.selectRange(range[0], range[1]);
                }
            }
        }]
	});
	
	function getSelectionRange(store, field, selectValue) {
		var count = store.getTotalCount();
		var start = -1;
		var end = -1;
		for(i = 0; i < count; i++) {
			if(store.getAt(i).data[field]==selectValue){
				if (start == -1) {
					start = i;
				}
				else {
					end = i;
				}
			}
		}
		if(end == -1) {
			end = start;
		}
		return [start, end];
	}
	
	gridwin = Ext.create('Ext.Window', {
		maximizable: true,
		iconCls: 'icon-detail',
        title: str_housekeeperdetail_xfmx,
        height: 550,
        width: 600,
        layout: 'fit',
        items: [grid],
        closeAction: 'hide',
        x: 10,
        y: 30,
        listeners:{
        	hide:function(){
        		if(showDetailGridBtn.pressed){
        			showDetailGridBtn.toggle();
        		}
        	}
        }
    }).show();
	
	chatwin = Ext.create('Ext.Window', {
		maximizable: true,
        title: str_housekeeperdetail_mxtu,
        height: 400,
        iconCls: 'icon-pie',
        width: 400,
        layout: 'fit',
        items: [monthChart],
        closeAction: 'hide',
        x: 620,
        y: 30,
        listeners:{
        	hide:function(){
        		if(showDetailChartBtn.pressed){
        			showDetailChartBtn.toggle();
        		}
        	}
        }
    }).show();
	query();
	
	showDetailGridBtn = new Ext.create('Ext.button.Button',{
		text: str_housekeeperdetail_mxb,
		iconCls: 'icon-detail',
		pressed: true,
        enableToggle: true,
		listeners:{
			click: function(){
				if(gridwin.isHidden()){
					gridwin.show();
				}
				else {
					gridwin.hide();
				}
			}
		}
	});
	
	showDetailChartBtn = new Ext.create('Ext.button.Button',{
		text: str_housekeeperdetail_mxtu,
		iconCls: 'icon-pie',
		pressed: true,
        enableToggle: true,
        listeners:{
			click: function(){
				if(chatwin.isHidden()){
					chatwin.show();
				}
				else {
					chatwin.hide();
				}
			}
		}
	});
	
	var panel = Ext.create('Ext.panel.Panel',{
		region: 'center',
		dockedItems: [
		    {
				xtype: 'toolbar',
				dock: 'top',
				items:[
                    showDetailGridBtn,'-',showDetailChartBtn, '-',statisticBtn
				]
		    }
		]
	});
	
	var view = Ext.create('Ext.container.Viewport', {
		layout : 'border',
		renderTo : Ext.getBody(),
		items : [panel]
	});
});